package ldh.im.base.handler.service;

import io.netty.channel.Channel;
import ldh.im.base.ImSession;
import ldh.im.base.SessionManager;
import ldh.im.base.service.BusinessService;
import ldh.im.base.service.BusinessServiceFactory;
import ldh.im.dto.DtoData;
import ldh.im.dto.codec.CodecFactory;
import ldh.im.dto.enmus.HandleType;

import java.util.List;

public abstract class BaseHandlerService implements HandlerService {

    public void doHandle(Channel channel, DtoData dtoData) {
        ImSession imSession = SessionManager.getInstance().getImSession(channel);
        HandleType handleType = CodecFactory.getInstance().getHandleType(dtoData.getCoder());
        if (handleType == HandleType.remote) {
            doBusiness(channel, imSession, dtoData.getByteBuf());
        } else if (handleType == HandleType.local) {
            Object obj = CodecFactory.getInstance().getTransfer(dtoData.getCoder()).getImCoder().decode(dtoData.getByteBuf());
            doBusiness(channel, imSession, obj);
        } else {
            throw new RuntimeException("不支持这种类型:" + dtoData.getCoder());
        }
    }

    private void doBusiness(Channel channel, ImSession imSession, Object obj) {
        List<BusinessService> businessServiceList = BusinessServiceFactory.getInstance().getHandlerServices(obj.getClass());
        for(BusinessService businessService : businessServiceList) {
            businessService.handle(imSession, obj);
        }
    }
}
